﻿/**
* ...
* @author Default
* @version 0.1
*/

package bdz.common.utils{
	import flash.display.Shape;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.text.TextField;
	import bdz.common.effects.RandomStringSequence;
	import flash.text.TextFormat;
	import flash.utils.*;
	
	//
	public class TextAnimator extends EventDispatcher {
		private var slotinterval:Number;
		private var piecer:Number;
		private var current:Number;
		private var joiner:Array;
		private var len:Number;
		private var enterFramer:Shape;
		private var slfield:TextField;
		private var slprop:String;
		private var slstr:String;
		function TextAnimator(){
			
		}
		private function slotTypography(field:TextField, prop:String, len:Number, str:String, joiner:Array):void{
			if(field == null){
				clearInterval(slotinterval);
			}
			if(current < len){
				joiner[current] = new Object();
				var cstr:String = str.charAt(current);
				new RandomStringSequence(cstr, 20, joiner[current], "text");
				current++;
			}else{
				clearInterval(slotinterval);
				dispatchEvent(new Event(Event.COMPLETE));
			}
		}
		
		private function assignSlotValues(evt:Event):void{
			if(slfield == null){
				clearInterval(piecer);
				enterFramer.removeEventListener(Event.ENTER_FRAME, assignSlotValues);
			}
			if(slfield[slprop] != slstr){
				slfield[slprop] = "";
				for each(var obj:* in joiner){
					if(obj.text){
						slfield[slprop] += obj.text;
					}
				}
			}else{
				enterFramer.removeEventListener(Event.ENTER_FRAME, assignSlotValues);
			}
		}
		private function pieceTypography(field:TextField, prop:String, len:Number, str:String, format:TextFormat):void{
			if(field == null){
				clearInterval(piecer);
			}
			if(current < len){
				var cstr:String = str.charAt(current);
				field[prop] += cstr;
				current++;
				if(format){
					field.setTextFormat(format);
				}
				dispatchEvent(new Event(Event.RENDER));
			}else{
				clearInterval(piecer);
				if(format){
					field.setTextFormat(format);
				}
				dispatchEvent(new Event(Event.COMPLETE));
			}
		}
		public function pieceByPiece(str:String, field:TextField, prop:String, format:TextFormat = null, speed:Number = 10):void{
			len = str.length;
			field[prop] = "";
			current = 0;
			slotinterval = setInterval(pieceTypography, speed, field, prop, len, str, format);
		}
		public function slotrandomize(str:String, field:TextField, prop:String, format:TextFormat = null):void{
			slstr = str;
			slfield = field;
			slprop = prop;
			field[prop] = "";
			len = str.length;
			current = 0;
			joiner = new Array();
			enterFramer = new Shape();
			enterFramer.addEventListener(Event.ENTER_FRAME, assignSlotValues);
			piecer = setInterval(slotTypography, 5, field, prop, len, str, joiner);
		}
	}
	
}